package client_core

import (
	"context"
	"fmt"
	"github.com/chicken-team-outside/chicken_transmission/api_messages"
	"github.com/chicken-team-outside/chicken_transmission/client_core/config"
	"github.com/chicken-team-outside/chicken_transmission/sfs"
	"go.uber.org/zap"
	"net/url"
)

var sfsClient = sfs.NewFsProvider(onConnectClose, onClientStatusChange)

func initSfsClient() {
	err := connectRpcServer(context.Background())
	if err != nil {
		zap.L().Warn("Failed to connect to sfs provider", zap.Error(err))
	}
}

func connectRpcServer(ctx context.Context) error {
	cfg := config.RpcServerConfig()
	return connectRpcServerByConfig(ctx, cfg)
}

func connectRpcServerByConfig(ctx context.Context, cfg *config.RpcServerSetting) error {
	parse, err := url.Parse(cfg.Address)
	if err != nil {
		return err
	}
	if parse.Scheme == "http" {
		parse.Scheme = "ws"
	} else if parse.Scheme == "https" {
		parse.Scheme = "wss"
	} else {
		return fmt.Errorf("unsupported scheme %s", parse.Scheme)
	}
	parse.Path = "/api/v1/rpc/msg"
	parse.RawQuery = ""
	sendRpcStatusChange(ServiceStatusConnecting)
	err = sfsClient.Connect(ctx, parse.String(), cfg.Token)
	if err == nil {
		sendRpcStatusChange(ServiceStatusSuccess)
	} else {
		sendRpcStatusChange(ServiceStatusFailure)
	}
	return err
}

func GetSfsClient() *sfs.FsClient {
	return sfsClient
}

func onConnectClose() {
	sendRpcStatusChange(ServiceStatusFailure)
}

func onClientStatusChange(msgType api_messages.MessageType, data interface{}) {
	sendEventData("on_client_status_change", msgType, data)
}
